<?php
class MTController extends commonController {
######################################################### 必接接口 订单推送API START ########################################################
    const SANDBOX_APP_ID = '4747';
    const SANDBOX_APP_SECRET = 'e201af79e7cc137c94606169660cfc03';
    const SANDBOX_URL = 'https://waimaiopen.meituan.com/api/v1/';
    const SANDBOX_STORE_ID = 't_MwlN3Lr8kI';

    const APP_ID = '4747';
    const APP_SECRET = 'e201af79e7cc137c94606169660cfc03';
    const URL = 'https://waimaiopen.meituan.com/api/v1/';
    const STORE_ID = 't_MwlN3Lr8kI';

    const PRINT_URL = '?md=service&cl=GetMTOrder&at=OrderData';

    /**
     * 推送已确认订单  的回调（自动确认订单支付之后）   ok 处理订单
     */
    public function MTConfirmOrderAction() {
        $config = Config::getInstance();
        $website_array = $config->getWebSiteConfig();
        $log = new Logging();
        $log->lfile('MTConfirmOrder');
        $log->lwrite('params:' . json_encode($this->params,JSON_UNESCAPED_UNICODE));
        if($this->params && $this->params['sig'] && count((array)$this->params) > 0){
            $real_time = '';
            $where = array('AND' => array('=' => array('ph_no' => 'MT'.$this->params['order_id'], 'shop_no' => $this->params['app_poi_code'], 'isdeleted' => 0)));
            $info = $this->model->getItemByOther($where, 'orders');
            if ($info && count((array)$info) > 0) {
                $m = $this->params['order_id'].' 该订单已被添加';
                $log->lwrite('订单号:' . $m);
                $r = ['data'=>'ok'];
                echo json_encode($r);
                exit;
            }else{
                $url_detail = urldecode($this->params['detail']);
                $detail = json_decode($url_detail,true);
                $extras = urldecode($this->params['extras']);
                $special = json_decode($extras,true);
                $SpecialRemark = '';
                if($special && count($special)>0){
                    foreach ($special as $s){
                        if($s){
                            $SpecialRemark .= $s['remark'];
                        }
                    }
                }
                $field['order_no'] = $this->params['order_id'];
                $field['shop_no'] = $this->params['app_poi_code'];
                $field['lat'] = $this->params['latitude'];
                $field['lng'] = $this->params['longitude'];
                $field['source'] = '美团';
                $field['buyer'] = urldecode($this->params['recipient_name']);
                $field['receiver'] = urldecode($this->params['recipient_name']);
                $field['receiver_tel'] = $this->params['recipient_phone'];

                $city = strstr(urldecode($this->params['recipient_address']),'@#',false);
                $address = strstr(urldecode($this->params['recipient_address']),'@#',true);
                $recipient_address = $city.$address;
                $field['receiver_address'] = str_replace('@#','',$recipient_address);

                $field['customre_memo'] = urldecode($this->params['caution']);
                $field['actual_pay'] = $this->params['total'];
                $field['order_time'] = date('Y-m-d H:i:s',$this->params['ctime']);
                if($this->params['delivery_time'] > 0){
                    $delivery_time = date('Y-m-d H:i:s',$this->params['delivery_time']);
                    $real_time = '';
                }else{
                    $delivery_time = date('Y-m-d H:i:s');
                    $real_time = '即时单';
                }
                $field['delivery_time'] = $delivery_time;
                $field['consignment_sync'] = 'Y';
                $field['status'] = 0;
                $field['shop_no'] = ($website_array['debug'])?100046:$this->params['app_poi_code'];
                $field['shop_name'] = urldecode($this->params['wm_poi_name']);
                $field['ph_no'] = 'MT'.$this->params['order_id'];
                $field['pos_fee'] = $this->params['shipping_fee'];
                $field['day_seq'] = $this->params['day_seq'];
                $field['backup_recipient_phone'] = urldecode($this->params['backup_recipient_phone']);
                $field['taxpayer_id'] = urldecode($this->params['taxpayer_id']);
                $field['invoice_title'] = urldecode($this->params['invoice_title']);
                $field['special'] = $SpecialRemark;

//                $o = $this->EXGold(urldecode($this->params['wm_poi_address'])); # 美团商家地址
                $where = array("AND" => array("=" => array( 'store_id' => $field['shop_no'])));
                $rsp_row = $this->model->getItemByOther($where, 'xd_store');
                $log->lwrite('store_info:' . json_encode($rsp_row,JSON_UNESCAPED_UNICODE));
                $StoreAddress = $rsp_row[0]['front_province']. $rsp_row[0]['front_city']. $rsp_row[0]['front_area']. $rsp_row[0]['front_address'];
                $log->lwrite('send_address:' . $StoreAddress);
                $o = $this->EXGold($StoreAddress); # 宅配地址
                $log->lwrite('areceive_address:' . json_encode($o,JSON_UNESCAPED_UNICODE));
                if($o && count($o) > 0 ){
                    $lng = round($o[0],5);
                    $lat = round($o[1],5);
                    $distance = $this->getdistanceAction($this->params['longitude'],$this->params['latitude'], $lng, $lat);
                    $log->lwrite('distance:' . $distance);
                    $distance = round($distance,2);
                    $field['distance'] = $distance;
                }else {
                    $field['distance'] = '';
                }

                $field['createdt'] = 'now()';
                $OID = $this->model->addItem($field, 'orders');



                $field_detail = [];
                foreach ($detail as $v){
                    $field_detail['orders_id'] = $OID;
                    $field_detail['product_no'] = $v['app_food_code'];
                    $field_detail['product_name'] = $v['food_name'];
                    $field_detail['pastry'] = $v['food_property'].'; 规格: '.$v['spec'];
                    $field_detail['qty'] = $v['quantity'];
                    $field_detail['unit_price'] = $v['price'];
                    $field_detail['ph_no'] = 'MT'.$this->params['order_id'];
                    $field_detail['createdt'] = 'now()';
                    $this->model->addItem($field_detail, 'orders_product');
                }

                # 推送打印系统
                $MTData = [];
                $field['real_time'] = $real_time;
                $MTData['version'] = 10;
                $MTData['check_code'] = strtoupper(substr( md5('shjieta'), 0, 16));
                $MTData['data'] = $field;
                $MTData['detail'] = $detail;
                $PrineURL = $website_array['website_print_url'].self::PRINT_URL;
                $r_print = self::MT_PUSH($PrineURL,json_encode($MTData),'json');

                $r_print = json_decode($r_print,true);
                if($r_print['errcode'] == 0)
                    $columns = ['mt_statu' => '1'];
               else
                    $columns = ['mt_statu' => '3'];

                $w = array("AND" => array("=" => array("id" => $OID)));
                $this->model->updateItem($columns, $w, 'orders');

                $r = ['data'=>'ok'];
                $log->lwrite('response:'.json_encode($r));
                echo json_encode($r);
            }
        }
    }

    private static function MT_PUSH($url, $param, $ContentType = ''){
        $log = new Logging();
        $oCurl = curl_init();
        if (stripos($url, "https://") !== FALSE) {
            curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, FALSE);
            curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, false);
            curl_setopt($oCurl, CURLOPT_SSLVERSION, 1); //CURL_SSLVERSION_TLSv1
        }
        if (empty($ContentType)) {
            curl_setopt($oCurl, CURLOPT_HTTPHEADER, array('application/x-www-form-urlencoded; charset=utf-8'));
        } else if ($ContentType == "json") {
            curl_setopt($oCurl, CURLOPT_HTTPHEADER, array('Content-Type: application/json; charset=utf-8'));
        }

        $strPOST='';
        if (is_string($param)) {
            $strPOST = $param;
        } else {
            $aGET = array();
            foreach ($param as $key => $val) {
                $aGET[] = $key . "=" . ($val);
            }
            $strPOST = join("&", $aGET);
        }

        curl_setopt($oCurl, CURLOPT_URL, $url);
        curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($oCurl, CURLOPT_CONNECTTIMEOUT, 60);
        curl_setopt($oCurl, CURLOPT_TIMEOUT, 60);
        curl_setopt($oCurl, CURLOPT_POST, true);
        curl_setopt($oCurl, CURLOPT_POSTFIELDS, $strPOST);
        curl_setopt($oCurl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);

        $time=strtotime(date('Y-m-d H:i:s'));
        $log->lfile('mtpush');
        $log->lwrite($time.','.($url));
        $log->lwrite($time.','.$strPOST);
        $sContent = curl_exec($oCurl);
        $aStatus = curl_getinfo($oCurl);
        $log->lwrite($time.' receive:'.($sContent));
        curl_close($oCurl);
        return $sContent;
    }



    /**
     * 已完成订单推送回调    ok
     */
    public function MTFinishStatusAction() {
        $log = new Logging();
        $log->lfile('MTFinishStatus');
        $r = ['data'=>'ok'];
        $log->lwrite('reception:' . json_encode($this->params,JSON_UNESCAPED_UNICODE).'response:'.json_encode($r));
        echo json_encode($r);
    }


    /**
     * 订单配送状态回调 未被调用
     */
    public function MTOrderStatusAction() {
        $log = new Logging();
        $log->lfile('MTOrderStatus');
        $r = ['data'=>'ok'];
        $log->lwrite('reception:' . json_encode($this->params,JSON_UNESCAPED_UNICODE).'response:'.json_encode($r));
        echo json_encode($r);
    }

    /**
     * 门店状态变更回调     ok
     */
    public function MTStoreStatusAction() {
        $log = new Logging();
        $log->lfile('MTStoreStatus');
        $r = ['data'=>'ok'];
        $log->lwrite('reception:' . json_encode($this->params,JSON_UNESCAPED_UNICODE).'response:'.json_encode($r));
        echo json_encode($r);
    }



   /**
     * 隐私号降级通知推送  可不接
     */
    public function MTPushNotificationAction() {
        $log = new Logging();
        $log->lfile('MTPushNotification');
        $r = ['data'=>'ok'];
        $log->lwrite('reception:' . json_encode($this->params,JSON_UNESCAPED_UNICODE).'response:'.json_encode($r));
        echo json_encode($r);
    }


    /**
     * 推送已支付订单  ok
     */
    public function MTPushPaidOrdersAction() {
        $log = new Logging();
        $log->lfile('MTPushPaidOrders');
        $this->MTConfirmAction($this->params['order_id']); # 直接确认订单
//        $this->MTCancelAction($this->params['order_id']); # 直接取消订单
        $r = ['data'=>'ok'];
        $log->lwrite('reception:' . json_encode($this->params,JSON_UNESCAPED_UNICODE).'response:'.json_encode($r));
        echo json_encode($r);
    }

    /**
     * 推送催单消息    ok
     */
    public function MTReminderAction() {
        $log = new Logging();
        $log->lfile('MTReminder');
        $r = ['data'=>'ok'];
        $log->lwrite('reception:' . json_encode($this->params,JSON_UNESCAPED_UNICODE).'response:'.json_encode($r));
        echo json_encode($r);
    }
######################################################### 订单推送API END ########################################################




######################################################### 取消订单推送API START ########################################################
    /**
     * 推送取消订单消息   推送用户或客服取消订单       ok
     */
    public function MTPushCancelOrderAction() {
        $log = new Logging();
        $log->lfile('MTPushCancelOrder');
        $r = ['data'=>'ok'];
        $log->lwrite('reception:' . json_encode($this->params,JSON_UNESCAPED_UNICODE).'response:'.json_encode($r));
        echo json_encode($r);
    }
######################################################### 取消订单推送API END ########################################################








######################################################### 退款信息推送API START ########################################################
    /**
     * 推送全额退款信息     ok
     */
    public function MTFullRefundAction() {
        $log = new Logging();
        $log->lfile('MTFullRefund');
        $this->MTAgreeAction($this->params['order_id'],$this->params['reason']);   # 确认退款
//        $this->MTRejectAction($this->params['order_id'],$this->params['reason']);   # 驳回退款
        $r = ['data'=>'ok'];
        $log->lwrite('reception:' . json_encode( $this->params ,JSON_UNESCAPED_UNICODE).'response:'.json_encode($r));
        echo json_encode($r);
    }

    /**
     * 推送部分退款信息 无法测试 APP 提示 只能整单退款
     */
    public function MTRebatesAction() {
        $log = new Logging();
        $log->lfile('MTRebates');
        $this->MTAgreeAction($this->params['order_id'],$this->params['reason']);   # 确认退款
//        $this->MTRejectAction($this->params['order_id'],$this->params['reason']);   # 驳回退款
        $r = ['data'=>'ok'];
        $log->lwrite('reception:' . json_encode($this->params,JSON_UNESCAPED_UNICODE).'response:'.json_encode($r));
        echo json_encode($r);
    }

######################################################### 退款信息推送API END ########################################################




######################################################### 必接接口 订单类API START ########################################################

    /**
     * 修改订单信息回调     *** 此接口为商家系统用于接收美团配送订单收货人信息变更消息的回调接口，仅适用于已接入美团配送的商家
     */
    public function MTEditOrderAction() {
        $log = new Logging();
        $log->lfile('MTEditOrder');
        $r = ['data'=>'ok'];
        $log->lwrite('reception:' . json_encode($this->params,JSON_UNESCAPED_UNICODE).'response:'.json_encode($r));
        echo json_encode($r);
    }


    /**
     * 商家确认订单   ok
     */
    public function MTConfirmAction($order_id) {
        $Config = Config::getInstance();
        $webSite = $Config->getWebSiteConfig();
        $APP_ID = (($webSite['debug']) ? self::SANDBOX_APP_ID : self::APP_ID);
        $URL = (($webSite['debug']) ? self::SANDBOX_URL : self::URL).'order/confirm';
        $parameter['order_id'] = $order_id;
        $parameter['timestamp'] = time();
        $parameter['app_id'] = $APP_ID;
        $log = new Logging();
        $log->lfile('MTConfirm');
        $sign = $this->_sign($parameter,$URL);
        $Result = $this->getCurl($sign);
        $Data = json_decode($Result, true);
        $log->lwrite('reception:' . json_encode($Data,JSON_UNESCAPED_UNICODE).'response:'.json_encode($parameter,JSON_UNESCAPED_UNICODE));
    }


    /**
     * 推送订单结算信息     ok
     */
    public function MTOrderCloseAction() {
        $log = new Logging();
        $log->lfile('MTOrderClose');
        $r = ['data'=>'ok'];
        $log->lwrite('reception:' . json_encode($this->params,JSON_UNESCAPED_UNICODE).'response:'.json_encode($r));
        echo json_encode($r);
    }



    /**
     * 驳回订单退款申请     ok
     */
    public function MTRejectAction($order_id,$reason) {
        $log = new Logging();
        $log->lfile('MTReject');
        $Config = Config::getInstance();
        $webSite = $Config->getWebSiteConfig();
        $APP_ID = (($webSite['debug']) ? self::SANDBOX_APP_ID : self::APP_ID);
        $URL = (($webSite['debug']) ? self::SANDBOX_URL : self::URL).'order/refund/reject';
        $parameter['order_id'] = $order_id;
        $parameter['reason'] = $reason;
        $parameter['timestamp'] = time();
        $parameter['app_id'] = $APP_ID;
        $sign = $this->_sign($parameter,$URL);
        $Result = $this->getCurl($sign);
        $Data = json_decode($Result, true);
        $r = ['data'=>'ok'];
        $log->lwrite('reception:' . json_encode($Data,JSON_UNESCAPED_UNICODE).'response:'.json_encode($parameter,JSON_UNESCAPED_UNICODE));

        echo json_encode($r);
    }



    /**
     * 订单确认退款请求     ok
     */
    public function MTAgreeAction($order_id,$reason) {
        $log = new Logging();
        $log->lfile('MTAgree');
        $Config = Config::getInstance();
        $webSite = $Config->getWebSiteConfig();
        $APP_ID = (($webSite['debug']) ? self::SANDBOX_APP_ID : self::APP_ID);
        $URL = (($webSite['debug']) ? self::SANDBOX_URL : self::URL).'order/refund/agree';
        $parameter['order_id'] = $order_id;
        $parameter['reason'] = $reason;
        $parameter['timestamp'] = time();
        $parameter['app_id'] = $APP_ID;
        $sign = $this->_sign($parameter,$URL);
        $Result = $this->getCurl($sign);
        $Data = json_decode($Result, true);
        $log->lwrite('reception:' . json_encode($Data,JSON_UNESCAPED_UNICODE).'response:'.json_encode($parameter,JSON_UNESCAPED_UNICODE));
    }



    /**
     * 拉取用户真实手机号    ok
     */
    public function MTBatchPullPhoneNumberAction() {
        $log = new Logging();
        $log->lfile('MTBatchPullPhoneNumber');
        $Config = Config::getInstance();
        $webSite = $Config->getWebSiteConfig();
        $APP_ID = (($webSite['debug']) ? self::SANDBOX_APP_ID : self::APP_ID);
        $STORE_ID = (($webSite['debug']) ? self::SANDBOX_STORE_ID : self::STORE_ID);
        $URL = (($webSite['debug']) ? self::SANDBOX_URL : self::URL).'order/batchPullPhoneNumber';
//        $parameter['app_poi_code'] = '';  # 非必填
        $parameter['offset'] = 0;       #   分页偏移量
        $parameter['limit'] = 100;      #   每页请求数
        $parameter['timestamp'] = time();
        $parameter['app_id'] = $APP_ID;
        $sign = $this->_sign($parameter,$URL);
        $sign = explode('&',$sign);
        $sign = array_pop($sign);
        $parameter['sig'] = substr($sign,strpos($sign,'=')+1);
        $Result = $this->http_post($URL,$parameter);        # 获取一个多维数组【结构：$Result['data'][多个]】
        $Data = json_decode($Result, true);
        $log->lwrite('reception:' . json_encode($Data,JSON_UNESCAPED_UNICODE).'response:'.json_encode($parameter));
    }



    /**
     * 商家取消订单     ok
     */
    public function MTCancelAction($order_id) {
        $Config = Config::getInstance();
        $webSite = $Config->getWebSiteConfig();
        $APP_ID = (($webSite['debug']) ? self::SANDBOX_APP_ID : self::APP_ID);
        $URL = (($webSite['debug']) ? self::SANDBOX_URL : self::URL).'order/cancel';
        $parameter['order_id'] = $order_id;
        $parameter['timestamp'] = time();
        $parameter['reason'] = '卖光了';
        $parameter['reason_code'] = 1001;
        $parameter['app_id'] = $APP_ID;
        $log = new Logging();
        $log->lfile('MTCancel');
        $sign = $this->_sign($parameter,$URL);
        $Result = $this->getCurl($sign);
        $Data = json_decode($Result, true);
        $log->lwrite('reception:' . json_encode($Data,JSON_UNESCAPED_UNICODE));
    }


    /**
     * 拉取骑手真实手机号
     */
    public function MTGetRiderInfoPhoneNumberAction() {
        $log = new Logging();
        $log->lfile('MTGetRiderInfoPhoneNumber');
        $Result = file_get_contents("php://input");
        $Data = json_decode($Result, true);
        $r = ['data'=>'ok'];

        echo '<pre>';
        var_dump($Data);
        $log->lwrite('reception:' . json_encode($Data,JSON_UNESCAPED_UNICODE).'response:'.json_encode($r));
        echo json_encode($r);
    }


    /**
     * 订单配送中 改状态   ok  无信息展示个 给客户     无订单配送状态推送过来 让API 回调 MTOrderStatus 接口
     */
    public function MTAeliveringAction() {
        $Config = Config::getInstance();
        $webSite = $Config->getWebSiteConfig();
        $log = new Logging();
        $log->lfile('MTAelivering');
        $APP_ID = (($webSite['debug']) ? self::SANDBOX_APP_ID : self::APP_ID);
        $URL = (($webSite['debug']) ? self::SANDBOX_URL : self::URL).'order/delivering';
        $parameter['order_id'] = '27009292362162587';
        $parameter['timestamp'] = time();
        $parameter['courier_name'] = '是我';
        $parameter['courier_phone'] = 17321295203;
        $parameter['app_id'] = $APP_ID;
        $sign = $this->_sign($parameter,$URL);
        $Result = $this->getCurl($sign);
        $Data = json_decode($Result, true);
        $log->lwrite('reception:' . json_encode($Data,JSON_UNESCAPED_UNICODE).'response:'.json_encode($parameter));
    }

    /**
     * 修改状态送达   ok      无订单配送状态推送过来 让API 回调 MTOrderStatus 接口
     */
    public function MTArrivedAction() {
        $Config = Config::getInstance();
        $webSite = $Config->getWebSiteConfig();
        $log = new Logging();
        $log->lfile('MTArrived');
        $APP_ID = (($webSite['debug']) ? self::SANDBOX_APP_ID : self::APP_ID);
        $URL = (($webSite['debug']) ? self::SANDBOX_URL : self::URL).'order/arrived';
        $parameter['order_id'] = '27009292362162587';
        $parameter['timestamp'] = time();
        $parameter['app_id'] = $APP_ID;
        $sign = $this->_sign($parameter,$URL);
        $Result = $this->getCurl($sign);
        $Data = json_decode($Result, true);
        $log->lwrite('reception:' . json_encode($Data,JSON_UNESCAPED_UNICODE).'response:'.json_encode($parameter));
    }
######################################################### 订单类API END ########################################################





######################################################### 店铺相关 START ########################################################
    /**
     * 创建修改店铺       ok
     */
    public function MTSaveStoreAction(){
        $log = new Logging();
        $log->lfile('MTSaveStore');
        $Config = Config::getInstance();
        $webSite = $Config->getWebSiteConfig();
        $APP_ID = (($webSite['debug']) ? self::SANDBOX_APP_ID : self::APP_ID);
        $URL = (($webSite['debug']) ? self::SANDBOX_URL : self::URL).'poi/save';

        $parameter['app_poi_code'] = '100046';  # APP方门店ID，最长不超过128个字符
        $parameter['name'] = '朱泾店修改测试';  # 是 门店名称
        $parameter['address'] = '上海金山区万安街634号';  # 是 门店地址
        $parameter['latitude'] = 30.8971;  # 是 门店纬度 （美团使用的是高德坐标系，也就是火星坐标系，如果是百度坐标系需要转换）(门店坐标不需要乘以一百万)
        $parameter['longitude'] = 121.16630;  # 是 门店经度
//        $parameter['pic_url'] = '';  # 否 门店头图图片地址
//        $parameter['pic_url_large'] = '';  # 否 logo
        $parameter['phone'] = '17321295203';  # 是 客服电话号码
        $parameter['shipping_fee'] = 0.2;  # 是 每个订单的配送费
        $parameter['shipping_time'] = '7:00-22:00';  # 是 7:00-9:00,11:30-19:00  门店营业时间 （注意格式，且保证不同时间段之间不存在交集）
//        $parameter['promotion_info'] = '';  # 否 门店推广信息
        $parameter['open_level'] = 1;  # 是 门店的营业状态：1为可配送，3为休息中
        $parameter['is_online'] = 1;  # 是 门店上下线状态：1为上线，0为下线，门店必须在菜品、配送范围和门店信息都齐全后，才能提交上线 （注意：此字段不为1时门店不会提交审核）
//        $parameter['invoice_support'] = '';  # 否 门店是否支持发票
//        $parameter['invoice_min_price'] = '';  # 否 门店支持开发票的最小订单价（invoice_suport为1时可用）
//        $parameter['invoice_description'] = '';  # 否 发票相关说明（invoice_support为1时可用）     发票特殊说明，如只有定额发票，不支持开抬头等
        $parameter['third_tag_name'] = '快餐简餐';  # 是 APP方品类名称需要根据接口“list 获取门店品类列表”获取门店品类列表接口获得，如果一个门店包含多个品类须以英文逗号隔开，如中餐,西餐
        # 目前最多支持上传两个门店品类：一个主营品类（上传的第一个品类为主营品类），一个辅营品类；部分门店品类只支持上传一个品类（例如：火锅，特色菜，地方菜，东南亚菜，日韩料理，生活超市）
//        $parameter['pre_book'] = '';  # 否 是否支持营业时间范围外预下单，1表支持，0表不支持
//        $parameter['time_select'] = '';  # 否 是否支持营业时间范围内预下单，1表支持，0表不支持，此字段开启后不可关闭，新建门店将自动开启
//        $parameter['app_brand_code'] = '';  # 否 第三方品牌code值（对接的三方需要提前将该值告诉美团技术同学）

        $parameter['timestamp'] = time();
        $parameter['app_id'] = $APP_ID;
        $sign = $this->_sign($parameter,$URL);
        $sign = explode('&',$sign);
        $sign = array_pop($sign);
        $parameter['sig'] = substr($sign,strpos($sign,'=')+1);
        $Result = $this->http_post($URL,$parameter);
        var_dump($Result);

        $Data = json_decode($Result, true);
        $log->lwrite('reception:' . json_encode($Data,JSON_UNESCAPED_UNICODE).'response:'.json_encode($parameter));
    }

    /**
     * 获取门店列表       ok
     */
    public function MTPoiMgetAction(){
        $log = new Logging();
        $log->lfile('MTPoiMget');
        $Config = Config::getInstance();
        $webSite = $Config->getWebSiteConfig();
        $APP_ID = (($webSite['debug']) ? self::SANDBOX_APP_ID : self::APP_ID);
        $URL = (($webSite['debug']) ? self::SANDBOX_URL : self::URL).'poi/mget';
        $parameter['app_poi_codes'] = "100046,";   # APP方门店id(半角逗号分隔)
        $parameter['timestamp'] = time();
        $parameter['app_id'] = $APP_ID;
        $sign = $this->_sign($parameter,$URL);
        $Result = $this->getCurl($sign);
        $Data = json_decode($Result, true);
        var_dump($Data);
        $log->lwrite('reception:' . json_encode($Data,JSON_UNESCAPED_UNICODE).'response:'.json_encode($parameter));
    }



    /**
     * 获取门店品类列表     ok
     */
    public function MTPoiTagListAction(){
        $log = new Logging();
        $log->lfile('MTPoiTagList');
        $Config = Config::getInstance();
        $webSite = $Config->getWebSiteConfig();
        $APP_ID = (($webSite['debug']) ? self::SANDBOX_APP_ID : self::APP_ID);
        $URL = (($webSite['debug']) ? self::SANDBOX_URL : self::URL).'poiTag/list';
        $parameter['timestamp'] = time();
        $parameter['app_id'] = $APP_ID;
        $sign = $this->_sign($parameter,$URL);
        $sign = explode('&',$sign);
        $sign = array_pop($sign);
        $parameter['sig'] = substr($sign,strpos($sign,'=')+1);
        $Result = $this->http_post($URL,$parameter);
        $Data = json_decode($Result, true);
        var_dump($Data);
        $log->lwrite('reception:' . json_encode($Data,JSON_UNESCAPED_UNICODE).'response:'.json_encode($parameter));
    }

######################################################### 店铺相关 END ########################################################




    /**
     * 签名生成
     * @param $parameter  数组参数
     * @return string
     */
    private function _sign($parameter,$URL){
        $Config = Config::getInstance();
        $webSite = $Config->getWebSiteConfig();
        $APP_SECRET = (($webSite['debug']) ? self::SANDBOX_APP_SECRET : self::APP_SECRET);
        # 升序排序
        ksort($parameter);
        # 字符串拼接
        $args = "$URL";
        foreach ($parameter as $key => $value) {
            $args.= '&'.$key.'='.$value;
        }
        $args = $result = substr_replace($args,"?",strpos($args,"&"),strlen("&"));;
        $args .= $APP_SECRET;
        $sign = md5($args);
        $args = str_replace($APP_SECRET,'',$args);
        $args .= '&sig='.$sign;
        return $args;
    }




    /**
     * POST 请求 API
     * @param $url
     * @param $post_data
     * @return bool|string
     */
    private function http_post($url, $post_data) {
        $header_data[]  =  "application/x-www-form-urlencoded";
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header_data);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post_data));
        $sResult = curl_exec($ch);
        $info = curl_getinfo($ch);
        if($sError=curl_error($ch)){
            die($sError);
        }
        curl_close($ch);
        echo '<pre>';
        var_dump($sResult);
        return $sResult;
    }

    # 发送get请求
    private function getCurl($url){
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL,$url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        $result =  curl_exec($ch);
        curl_close ($ch);
        return $result;
    }

    # 兑换高德经纬度
    private function EXGold($address){
        include_once ('plugin/GaoDeAPIClass.php');
        $log = new Logging();
        $log->lfile('EXGold');
        if(strstr($address,'(')){
            $address = strstr($address,'(',true);
        }
        if(strstr($address,'（')){
            $address = strstr($address,'（',true);
        }

        $address = str_replace(' ','',$address);
        $log->lwrite(date('Y-m-d H:i:s').'  ad：'.$address.'');
        $GaoDeAPI = new GaoDeAPI();
        $r = $GaoDeAPI->getTrapezeAction($address);
        $location = [];
        if($r && count($r) > 0){
            $location = explode(',',$r['geocodes'][0]['location']);
        }
        $log->lwrite(date('Y-m-d H:i:s').'  res：'.json_encode($location,JSON_UNESCAPED_UNICODE).'');
        if($location && is_array($location) && count($location) > 1){
            return $location;
        }else{
            return '';
        }

    }

    /**
     * 求两个已知经纬度之间的距离,单位为米
     * @param lng1 $ ,lng2 经度
     * @param lat1 $ ,lat2 纬度
     * @return float 距离，单位米
     */
    private function getdistanceAction($lng1, $lat1, $lng2, $lat2) {
        $radLat1 = deg2rad($lat1);
        $radLat2 = deg2rad($lat2);
        $radLng1 = deg2rad($lng1);
        $radLng2 = deg2rad($lng2);
        $a = $radLat1 - $radLat2;
        $b = $radLng1 - $radLng2;
        $s = 2 * asin(sqrt(pow(sin($a / 2), 2) + cos($radLat1) * cos($radLat2) * pow(sin($b / 2), 2))) * 6378.137 * 1000;
        return $s;
    }
}